#include "httpparser.h"
#include "loger.h"
#include "dispatcherservlet.h"
HttpParser::HttpParser(QObject *parent) : QObject(parent)
{
    dispacherServlet = new DispatcherServlet(this);
}
HttpParser::~HttpParser(){

    QString info("HttpParser已析构");
    Loger::info(info);
}
/**
 * 解析请求参数
 * @brief parseParams
 * @param paramsLine
 */
void HttpParser::parseParams(HttpRequest * request, QString& paramsLine){
    QStringList paramsList = paramsLine.split("&");
    for(QString p : paramsList){
        if(p.contains("=")){
            QStringList paramList = p.split("=");
            request->params.insert(paramList[0], paramList[1]);
        }

    }
}
/**
 * 创建request对象
 * @brief createHttpRequest
 * @param conn
 * @return
 */
void  HttpParser::createHttpRequest(HttpRequest * request, Connection * conn){
    //解析
    const int bufSize = 256;
    char  buf[bufSize]={0};
    conn->readLine(buf, bufSize);
    QString s(buf);
    QStringList list = s.split(QRegExp(" "));

    //请求方式
    if(list[0].startsWith("GET")){
        request->requestMethod = HttpRequest::RequestMethod::GET;

    }else if(list[0].startsWith("POST")){
        request->requestMethod = HttpRequest::RequestMethod::POST;
    }

    //解析请求参数
    if(list[1].contains("?")){
        QStringList uriList = list[1].split("?");
        request->requestUri = uriList[0];//请求uri
        parseParams(request, uriList[1]); //参数解析

    }else{
        request->requestUri = list[1]; //请求uri
    }
    QString info("请求URI:");
    info.append(request->requestUri);
    Loger::info(info);

    //请求头
    memset(buf, 0, bufSize);
    while(conn->readLine(buf,256)){
        QString header(buf);
        if(header.compare("\r\n") == 0){
            break;
        }
        QStringList list = header.split(QRegExp(": "));
        request->requestHeader.insert(list[0], list[1]);
        memset(buf, 0, bufSize);
    }

    //post参数解析
    if(request->getRequestMethod() == HttpRequest::POST){
        QString body;
        while(conn->read(buf, bufSize) >0){
            body.append(buf);
        }
         parseParams(request, body); //参数解析
    }
}
 /**
 * 服务
 * @brief service
 */
void  HttpParser::service(Connection *conn){
    HttpRequest * request = new HttpRequest(this);
    request->conn = conn;
    HttpResponse * response = new HttpResponse(this);
    response->conn = conn;
    //封装请求对象
    createHttpRequest(request, conn);
    response->statusCode = 200;
    //调用servlet
    dispacherServlet->doService(request, response);
    //封装响应对象
    request->deleteLater();
    response->deleteLater();
}
